<template>
<div>
    <el-card class="box-card">
        <!-- 卡片顶部添加品牌按钮 -->
        <el-button type="primary" size="default" icon="Plus" @click="addTrademark()">添加品牌</el-button>
        
        <!-- 表格组件：用于展示已有得平台数据 -->
        <el-table style="margin:10px 0px" border :data="trademarkArr">
            <el-table-column label="序号" width="80px" align="center" type="index"> </el-table-column>
            
            <el-table-column label="品牌名称" prop="tmName"> </el-table-column>

            <el-table-column label="品牌LOGO">
                <template #="{ row, $index }">
                    <img :src="row.logoUrl" style="width:100px;height: 100px;">
                </template>
            </el-table-column>

            <el-table-column label="品牌操作">
                <template #="{ row, $index }">
                    <!-- 修改按钮 -->
                    <el-button type="primary" size="small" icon="Edit" @click="updataTrademark(row)"></el-button>
                    <!-- 删除按钮 -->
                    <el-popconfirm :title="`您确定要删除${row.tmName}?`" width="250px" icon="Delete" @confirm="removeTrademark(row.id)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>

        </el-table>

        <!-- 分页器组件
            v-model:current-page:设置分页器当前页码
            v-model:page-size:设置每一个展示数据条数
            page-sizes:用于设置下拉菜单数据
            background:设置分页器按钮的背景颜色
            layout:可以设置分页器六个子组件布局调整

            【v-model:】 在双向绑定的同时向子组件传递数据
        -->
        <el-pagination 
            :pager-count="9"
            v-model:current-page="pageNo"
            v-model:page-size="limit"
            :page-sizes="[3, 5, 7, 9]"
            :background="true"
            layout="prev, pager, next, jumper,->,sizes,total"
            :total="total"
            @current-change="getHasTrademark"
            @size-change="sizeChange"
        />
    </el-card>

    <el-dialog
        v-model="dialogVisible"
        :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
        width="500"
    >
        <el-form style="padding: 20px 50px; box-sizing: border-box;" :model="trademarkParams" label-width="auto"  :rules="rules" ref="formRef">
            <el-form-item label="品牌名称：" prop="tmName">
                <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
            </el-form-item>
            <el-form-item label="品牌Logo：" prop="logoUrl">
                <!-- 
                    action：图片上传地址
                    before-upload：上传之前钩子：用于限制文件格式、大小等
                    on-success：上传成功后的钩子
                -->
                <el-upload
                    class="avatar-uploader"
                    action="/upload/admin/product/fileUpload"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccess"
                >
                    <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>

                <el-button type="primary" @click="confirm"> 确定 </el-button>
            </div>
        </template>
    </el-dialog>

</div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, reactive, nextTick } from 'vue';
import {reqHasTrademark, reqAddOrUpdataTrademark, reqDelTrademark} from '@/api/product/trademark'
import {Records, TradeMark, TradeMarkResponseData} from '@/api/product/trademark/type'
import { ElMessage, type UploadProps } from 'element-plus'
//当前页码
let pageNo = ref<number>(1);
//每一页展示多少条数据
let limit = ref<number>(3);
//存储已有品牌总数
let total = ref<number>(0);
//存储已有品牌的数据
let trademarkArr = ref<Records>([]);
// let trademarkArr = reactive<any>([]);
// 定时器对象
let timeoutObj = ref<ReturnType<typeof setTimeout> | null>(null);
// 对话框展示控件
let dialogVisible = ref<boolean>(false)
// 新增或删除 的品牌对象
let trademarkParams = reactive<TradeMark>({
    tmName: '',
    logoUrl: ''
})
// form组件实例
let formRef = ref()

// 表单rules：校验品牌的方法
const validatorTmName = (rule: any, value: any, callback: any)=>{
    console.log(value);
    if(trademarkParams.tmName.trim().length >= 2){
        callback()
    }else{
        callback(new Error('品牌名称大于两位'))
    }
}

// 表单rules：校验图片的方法
const validatorLogoUrl = (rule: any, value: any, callback: any)=>{
    if(trademarkParams.logoUrl.trim().length >= 2){
        callback()
    }else{
        callback(new Error('请上传品牌图片'))
    }
}

// 表单校验规则
const rules = reactive({
    // required，是否必须校验，表单项会出现*号
    // trigger，校验的时机
    // validator，校验的方法
    tmName:[
        {required:true, trigger: 'blur', validator: validatorTmName}
    ],
    logoUrl:[
        {required:true, validator: validatorLogoUrl}
    ]
})


// 请求数据和切换页码时触发
const getHasTrademark = async(pager=1)=>{
    pageNo.value = pager

    // 清除之前的定时器（如果存在）  
    if (timeoutObj.value) {  
        clearTimeout(timeoutObj.value);  
    }

    timeoutObj.value = setTimeout( async()=>{
        let result: TradeMarkResponseData = await reqHasTrademark(pageNo.value, limit.value )
        if(result.code==200){
            total.value = result.data.total;
            trademarkArr.value = result.data.records;
        }
    },200)
}

// 切换页码大小
const sizeChange = ()=>{
    getHasTrademark()
}

// 添加品牌按钮
const addTrademark = ()=>{
    dialogVisible.value = true
    trademarkParams.tmName = ''
    trademarkParams.logoUrl = ''
    trademarkParams.id = undefined

    // 清除表单校验提示信息

    // 1、通过可选链的方式，避免第一次formRef还未渲染，而没有clearValidate方法，导致报错 
    // formRef.value?.clearValidate()

    // 2、通过nextTick 获得更新后的DOM
    nextTick(()=>{
        formRef.value.clearValidate()
    })

    // 放到取消按钮里
}

// 修改品牌按钮
const updataTrademark = async(row: TradeMark)=>{
    // 清除表单验证
    formRef.value?.clearValidate()
    // 收集修改参数，将table的row对象的属性和值赋予给trademarkParams
    Object.assign(trademarkParams, row)
    // 打开对话框
    dialogVisible.value = true
}

// 对话框--确定按钮
const confirm = async()=>{
    // 图片不是表单元素，无法使用基本的触发时机，通过点击确定按钮时，手动触发校验所有规则
    formRef.value.validate()

    let result:any = await reqAddOrUpdataTrademark(trademarkParams)
    if(result.code==200){
        // 关闭对话框
        dialogVisible.value = false
        // 提示信息
        ElMessage({
            type: 'success',
            message: trademarkParams.id ? '修改成功': '添加成功'
        })
        // 重新请求数据
        getHasTrademark(trademarkParams.id ? pageNo.value : 1)
    }else{
        dialogVisible.value = false
        ElMessage({
            type: 'error',
            message: trademarkParams.id ? '修改失败': '添加失败'
        })
    }
}

// 上传图片之前的回调，用于约束文件对象
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']; 
    if (!allowedTypes.includes(rawFile.type)) {
        ElMessage.error('请上传图片')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小超过2MB!')
        return false
    }
    return true
}

// 上传图片成功后的回调，用于获取数据，在此获取图片的服务器地址
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
    trademarkParams.logoUrl = response.data
    formRef.value.clearValidate('logoUrl')
}

// 删除品牌--气泡确认框--确定按钮
const removeTrademark = async(id:number)=>{
    let result:any =  await reqDelTrademark(id)
    if(result.code == 200){
        ElMessage({
            type: 'success',
            message: '删除品牌成功'
        })
        // 判断所处的页码，以及特殊情况 
        const pageNum = trademarkArr.value.length>1  ? pageNo.value : (pageNo.value > 1 ? pageNo.value - 1 : pageNo.value) 
        getHasTrademark(pageNum)
    }else{
        ElMessage({
            type: 'error',
            message: '删除品牌失败'
        })
    }
}


onMounted(()=>{
    getHasTrademark()
})

// 在组件卸载时清除可能存在的定时器（防止内存泄漏）  
onUnmounted(() => {  
  if (timeoutObj.value) {  
    clearTimeout(timeoutObj.value);  
    timeoutObj.value = null;  
  }  
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>